﻿using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System;
using Microsoft.Extensions.Configuration;
using Swashbuckle.AspNetCore.Swagger;
using System.Globalization;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
using Microsoft.AspNetCore.Builder;

namespace System
{

    public class JwtHelper
    {

        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static string CreateToken(TokenModelJwt tokenModel)
        {

            var claims = GetClaims(tokenModel);

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConfig.SecretKey));
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(JwtConfig.Issuer,
                JwtConfig.Audience, claims,
                expires: DateTime.Now.AddHours(JwtConfig.AccessExpiration),
                signingCredentials: cred);
            string token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return token;
        }
        public static List<Claim> GetClaims(TokenModelJwt tokenModel)
        {
            var claims = new List<Claim> {
                new Claim(ClaimTypes.GivenName,"login"),
                new Claim(ClaimsName.UserID, tokenModel.UserId.ToString()),
                new Claim(ClaimsName.UserName, tokenModel.UserName),
                new Claim(ClaimsName.Phone, tokenModel.Phone),
                new Claim(ClaimsName.Email, tokenModel.Email),
                new Claim(ClaimsName.LoginTime, DateTime.Now.ToString6()),
                new Claim(ClaimsName.TenantId, tokenModel.TenantId),
                new Claim(ClaimTypes.Name, tokenModel.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, tokenModel.UserId.ToString()),//Jwt唯一标识Id
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//令牌签发时间
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,//不早于的时间声明
                new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddHours(JwtConfig.AccessExpiration)).ToUnixTimeSeconds()}"),//令牌过期时间
                new Claim(ClaimTypes.Expiration, DateTime.Now.AddHours(JwtConfig.RefreshExpiration).ToString(CultureInfo.CurrentCulture)),//令牌截至时间
                new Claim(JwtRegisteredClaimNames.Iss,JwtConfig.Issuer),//发行人
                new Claim(JwtRegisteredClaimNames.Aud,JwtConfig.Audience),//订阅人
            };

            var roles = new List<Claim>();
            if (tokenModel.UserName == "admin")
            {
                roles.Add(new Claim(ClaimTypes.Role, "admin"));
            }
            else
            {
                roles.Add(new Claim(ClaimTypes.Role, "normal"));
            }
            claims.AddRange(roles);

            return claims;

        }

        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static TokenModelJwt SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object role = new object();
            object name = new object();
            object Exp = new object();
            object givenName = new object();
            try
            {
                jwtToken.Payload.TryGetValue(ClaimTypes.Name, out name);
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
                jwtToken.Payload.TryGetValue(JwtRegisteredClaimNames.GivenName, out givenName);
                jwtToken.Payload.TryGetValue(JwtRegisteredClaimNames.Exp, out Exp);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            var tm = new TokenModelJwt
            {
                UserId = jwtToken.Id.ToString(),
                UserName = name != null ? name.ToString() : "",
                Role = role != null ? role.ToString() : "",
                Exp = Convert.ToInt64(Exp)
            };
            return tm;
        }

        public static JwtSetting JwtConfig { get { return ConfigHelper.GetValue<JwtSetting>("JWTSetting"); } }
    }
    /// <summary>
    /// 令牌
    /// </summary>
    public class TokenModelJwt
    {
        public TokenModelJwt()
        {
            Phone = "";
            Email = "";
            TenantId = "";
            Work = "";
            Role = "";
            UserId = "";
            UserName = "";
        }
        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserId { get; set; }
        /// <summary>
        /// 用户名称
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 角色
        /// </summary>
        public string Role { get; set; }
        /// <summary>
        /// 职能
        /// </summary>
        public string Work { get; set; }
        public long Exp { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string TenantId { get; set; }
    }
    public class JwtSetting
    {
        /// <summary>
        /// 发行者
        /// </summary>
        public string Issuer { get; set; }
        /// <summary>
        /// 受众
        /// </summary>
        public string Audience { get; set; }
        /// <summary>
        /// 秘钥
        /// </summary>
        public string SecretKey { get; set; }
        /// <summary>
        /// 过期时间
        /// </summary>
        public int AccessExpiration { get; set; }
        /// <summary>
        /// 刷新时间
        /// </summary>
        public int RefreshExpiration { get; set; }
    }

    /// <summary>
    /// <code> app.UseMiddleware 《JwtTokenAuth》 ()  </code>
    /// </summary>
    public class JwtTokenAuth
    {
        // 中间件一定要有一个next，将管道可以正常的走下去
        private readonly RequestDelegate _next;
        public JwtTokenAuth(RequestDelegate next)
        {
            _next = next;
        }
        public Task Invoke(HttpContext httpContext)
        {
            // 检测是否包含'Authorization'请求头
            if (!httpContext.Request.Headers.ContainsKey("Authorization"))
            {
                return _next(httpContext);
            }
            try
            {
                var tokenHeader = httpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
                if (tokenHeader.Length >= 128)
                {
                    TokenModelJwt tokenModel = JwtHelper.SerializeJwt(tokenHeader);
                    var claims = JwtHelper.GetClaims(tokenModel);
                    var identity = new ClaimsIdentity(claims);
                    var principal = new ClaimsPrincipal(identity);
                    httpContext.User = principal;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"{DateTime.Now} middleware wrong:{e.Message}");
                throw;
            }
            return _next(httpContext);
        }
    }
    public static class MiddlewareHelpers
    {
        public static IApplicationBuilder UseJwtTokenAuth(this IApplicationBuilder app)
        {
            return app.UseMiddleware<JwtTokenAuth>();
        }
    }

}
